package com.xagent.engine;

import com.xagent.core.Entry;
import com.xagent.core.ThreadControl;
import com.xagent.core.context.AgentThreadContext;
import com.xagent.engine.context.AgentContext;
import com.xagent.engine.context.ThreadContext;
import com.xagent.engine.context.phase.GeneratorPhase;
import com.xagent.engine.hook.HookInfo;
import com.xagent.engine.policy.MethodContext;
import com.xagent.engine.utils.HookUtil;

import java.lang.instrument.Instrumentation;
import java.util.HashMap;

/**
 * Author: 4ut15m
 * Core to Engine.
 */
public class ReflectEntryB implements Entry, AgentThreadContext {
    private static ThreadLocal<ThreadContext> threadContext = new ThreadLocal<>();

    @Override
    public void entrance(Instrumentation instrumentation, String filePath) {

    }

    @Override
    public void entrance(Object returnObject, Object thisObject, Object[] args, boolean isEnter, int index, String className, String methodName, String methodDescirptor) {
        /**
         * start
         * 设置方法上下文
         * */
        MethodContext methodContext = new MethodContext(className, methodName, HookUtil.getDescriptorWithoutReturnType(methodDescirptor));
        methodContext.setParamObjects(args);
        methodContext.setIndex(index);
        methodContext.setThisObject(thisObject);
        HashMap<String, HashMap<String, HookInfo>> policyMap = AgentContext.getContext().getConfig().getPolicyMap();

        /**
         * end
         * */
        if (isEnter) {
            methodContext.setEnter(isEnter);
            if (HookUtil.getHookType(policyMap, methodContext.getClassName(), methodContext.getSignature()) == null)
                return;
            GeneratorPhase.generator(policyMap, methodContext, threadContext);
        } else {
            methodContext.setReturnObject(returnObject);
            GeneratorPhase.fill(policyMap, methodContext, threadContext);
        }

    }


}
